package com.supreme.orderserver.service;

import com.supreme.orderserver.service.remote.BizStockService;
import com.supreme.common.dto.UpdateGoodsStockDTO;
import com.supreme.common.entityVO.CreateOrderVO;
import com.supreme.commonboot.exception.BizException;
import com.supreme.commonmybatis.entity.primary.MBGoods;
import com.supreme.commonentity.mysql.primary.BizOrder;
import com.supreme.commonentity.mysql.primary.SysUser;
import com.supreme.commonmybatis.mapper.GoodsMapper;
import com.supreme.commonmybatis.mapper.UserMapper;
import com.supreme.commonmybatis.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class OrderService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private BizStockService bizStockService;

    @GlobalTransactional
    @Transactional(rollbackFor = BizException.class)
    public int createOrder(CreateOrderVO createOrderVO) {
        final Long userId = createOrderVO.getUserId();
        final Long goodsId = createOrderVO.getGoodsId();
        final Integer buyNum = createOrderVO.getBuyNum();

        final SysUser user = userMapper.selectById(userId);
        if (Objects.isNull(user)) {
            throw new BizException("user not found");
        }

        final MBGoods goods = goodsMapper.selectById(goodsId);
        if (Objects.isNull(goods)) {
            throw new BizException("goods not found");
        }

        final BizOrder order = new BizOrder();
        order.setOrderCode(String.valueOf(System.currentTimeMillis()));
        order.setOrderNum(buyNum);
        order.setOrderType(1);
        order.setUserId(userId);
        order.setGoodsId(goodsId);
        int result = orderMapper.insert(order);

        final UpdateGoodsStockDTO updateGoodsStockDTO = new UpdateGoodsStockDTO();
        updateGoodsStockDTO.setGoodsId(goodsId);
        updateGoodsStockDTO.setGoodsNum(buyNum);
        bizStockService.updateGoodsStock(updateGoodsStockDTO);

        return result;
    }
}
